package com.canieatit.app.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.zip.GZIPInputStream;

import org.apache.http.protocol.HTTP;

import android.util.Base64;
import android.util.Log;

public class BingSearch {
	private static final String TAG = "WebServices";
	private static final String BING_SEARCH_API_KEY = "AKu0p5/9GBGDQKZHQgNri0j+22aY+6/ukGEktcvCVLA=";
	
	static final int CONNECTION_TIMEOUT = 1000;
	static final int SOCKET_TIMOUT = 2000;
//	static DefaultHttpClient client = getThreadSafeClient();
	
	public static String httpGet(final String searchURL) throws IOException  {
		
		Log.d(TAG, "HttpGet URL: "+ searchURL);
		
		HttpURLConnection con = null;
		URL url;
		
		url = new URL(searchURL);
		con = (HttpURLConnection) url.openConnection();
		con.setReadTimeout(10000 /* milliseconds */);
		con.setConnectTimeout(15000 /* milliseconds */);
		con.setRequestMethod("GET");
//			con.setDoInput(true);
		con.addRequestProperty("Accept", "application/json");
		con.setRequestProperty("Authorization", "Basic "+ Base64.encodeToString((":"+BING_SEARCH_API_KEY).getBytes("UTF-8"),Base64.NO_WRAP));
		Log.d(TAG, "Basic "+ Base64.encodeToString((":"+BING_SEARCH_API_KEY).getBytes("UTF-8"),Base64.NO_WRAP));
		con.addRequestProperty(HTTP.CONTENT_TYPE, "application/json");	
		// Start the query
		con.connect();
		
		InputStream is = con.getInputStream();
		if ("gzip".equals(con.getContentEncoding())) {
			Log.i(TAG, "Response is Gzip encoded");
			is = new GZIPInputStream(is);
		}

		
		// Now convert the input stream to a String
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		String line;
		StringBuilder sb =  new StringBuilder();
		while ((line = rd.readLine()) != null) {
				sb.append(line);
		}
		rd.close();
		
		con.disconnect();
		 
		return sb.toString() ;	
		
	}

}
